package com.ky.tms.config;

import com.ky.tms.exception.PredictableException;
import com.ky.tms.util.CommonResult;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GloableExceptionController {

    //拦截系统类型异常
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<CommonResult> systemExceptionHandler(Exception ex){
        CommonResult failure = CommonResult.buildException(ExceptionUtils.getStackTrace(ex));
        ex.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failure);
    }

    //拦截业务类型异常
    @ExceptionHandler(value = PredictableException.class)
    public ResponseEntity<CommonResult> usinessExceptionHandler( Exception ex){
        CommonResult failure = CommonResult.buildError(ex.getMessage());
        ex.printStackTrace();
        return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).body(failure);
    }

    //运行时异常
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseEntity<CommonResult> runtimeExceptionHandler(Exception ex){
        CommonResult failure = CommonResult.buildError(ex.getMessage());
        ex.printStackTrace();
        return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).body(failure);
    }

    //重复key
    @ExceptionHandler(value = DuplicateKeyException.class)
    public ResponseEntity<CommonResult> duplicateKey(Exception ex){
        CommonResult failure = CommonResult.buildError("请注意唯一键约束！");
        ex.printStackTrace();
        return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).body(failure);
    }

}

